#include <PCBCache.h>
#include <csp_debug.h>
#include <csp_macros.h>
#include <csp_shared_types.h>
#include <csp_protocol_msg.h>

#include <malloc_align.h>
#include <malloc.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>

using namespace std;

#define SIZE 6000

#include <limits.h>		/* for CHAR_BIT */

#define BITMASK(b) (1 << ((b) % CHAR_BIT))
#define BITSLOT(b) ((b) / CHAR_BIT)
#define BITSET(a, b) ((a)[BITSLOT(b)] |= BITMASK(b))
#define BITCLEAR(a, b) ((a)[BITSLOT(b)] &= ~BITMASK(b))
#define BITTEST(a, b) ((a)[BITSLOT(b)] & BITMASK(b))
#define BITNSLOTS(nb) ((nb + CHAR_BIT - 1) / CHAR_BIT)


PCBCache::PCBCache()
{
	bitarray = (char*) malloc(sizeof(char)*BITNSLOTS(SIZE));
	pcb_cache_head = (pcb_t*) _malloc_align(sizeof(pcb_t)*SIZE, 7);
}

PCBCache::~PCBCache()
{
}

PCBCache* PCBCache::pinstance = 0;// initialize pointer

PCBCache* PCBCache::Instance () 
{
	if (pinstance == 0)  // is it the first call?
	{  
		pinstance = new PCBCache(); // create sole instance
	}
	return pinstance; // address of sole instance
}

pcb_t* PCBCache::Head()
{
	return pcb_cache_head;
}

int PCBCache::GetFreeIdx()
{
	int i;
	for(i=0; i < SIZE; i++){
		if( !BITTEST(bitarray, i) ){
			BITSET(bitarray, i);
			return i;
		}	
	}
	return -1;
}


